USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_rpad') BEGIN
	DROP  FUNCTION  tsql.fn_rpad
	PRINT '<<< DROP FUNCTION tsql.fn_rpad - Completed with SUCCESS >>>'
END
GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			tsql.fn_rpad
Type:			User defined function 
Owner:						
Description:	returns a string right padded to the specified number of characters
Parameters:		@string_to_pad = string to add pad characters to
				@pad_char = character(S) to use for padding
				@pad_to_len = final lenght of the string after padding
Dependens on:  	none
Usage:			SELECT [tsql].[fn_rpad] ('test','z',25)
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_rpad&referringTitle=Documentation		
Version:		20120822
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		11/30/2009 - Adrian E Dudau - Function created
History:		08/22/2012 - Adrian E Dudau - Added references to project, SVN and Help
================================================================================================*/

CREATE FUNCTION [tsql].[fn_rpad] 
	( @string_to_pad NVARCHAR(MAX)
	, @pad_char NVARCHAR(4000)
	 ,@pad_to_len BIGINT)

RETURNS NVARCHAR(MAX)
AS

BEGIN
	-- Reduce overhead by returning string unchanged
	IF LEN(@string_to_pad) >= @pad_to_len BEGIN 
		SET @pad_char = N''
	END

	RETURN @string_to_pad + REPLICATE(ISNULL(@pad_char,''),@pad_to_len - LEN(@string_to_pad)) 
END

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_rpad') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_rpad - Completed with SUCCESS >>>'
END

ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_rpad - Completed with ERROR >>>'
END

GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------
